package com.www.pagingdemo.data

import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.www.pagingdemo.api.GithubService
import com.www.pagingdemo.db.RepoDatabase
import com.www.pagingdemo.model.Repo
import kotlinx.coroutines.flow.Flow

/**
 * 使用本地和远程数据源的存储库类
 * @author MilkCoder
 * @date 2021-09-22
 */
class GithubRepository(
    private val service: GithubService,
    private val database: RepoDatabase
) {
    /**
     * 搜索名称与查询相匹配的存储库，
     * 当我们每次从网络获得更多数据时，
     * 存储库就会以数据流的形式出现
     * @date: 2021/9/22 17:37
     */
    fun getSearchResultStream(query: String): Flow<PagingData<Repo>> {
        // 添加'%'，以便允许其他字符在查询字符串之前和之后
        val dbQuery = "%${query.replace(' ', '%')}%"
        val pagingSourceFactory = { database.reposDao().reposByName(dbQuery) }

        @OptIn(ExperimentalPagingApi::class)
        return Pager(
            config = PagingConfig(pageSize = NETWORK_PAGE_SIZE, enablePlaceholders = false),
            remoteMediator = GithubRemoteMediator(
                query,
                service,
                database
            ),
            pagingSourceFactory = pagingSourceFactory
        ).flow
    }

    companion object {
        const val NETWORK_PAGE_SIZE = 30
    }
}